package com.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.config.SpringContextUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/25 12:35
 * @since JDK 1.8
 */
@Component
public class DBtemp {


    private static final String devPATH=System.getProperty("user.dir");

    /**
     * 数据库备份
     * @param
     * @return
     */
    public  String tempDB(){
        String filePath=devPATH+File.separator+"dbtemp";
        Map<String, String> dataSource= SpringContextUtils.getBeanObj("dbmap");
        String username=dataSource.get("username");
        String password=dataSource.get("password");
        String tableName=dataSource.get("tablename");
        String nowTime=Utils.getNowDateString();
        String cmd =  "mysqldump -u "+ username +"  -p"+password +" "+ tableName + " -r "
                + filePath + "/" + tableName+nowTime+ ".sql";
        String result=Utils.runTimeProcess(cmd);
        deleteOne();
        return result;
    }


    private  void deleteOne(){
        String filePath=devPATH+ File.separator+"dbtemp";
        File file=new File(filePath);
        String[] str=file.list();
        JSONArray jsonArray=new JSONArray();
        for (int i = 0; i < str.length; i++) {
            JSONObject jsonObject=new JSONObject();
            String fileName=str[i];
            jsonObject.put("file",filePath+File.separator+fileName);
            String s=str[i].replace("spring-demo","").replace(".sql","");
            SimpleDateFormat dft=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            try {
                Date date=dft.parse(s);
                jsonObject.put("time",date.getTime());
            }catch (Exception e){
                e.printStackTrace();
            }
            jsonArray.add(jsonObject);
        }
        List<JSONObject> list=JSONArray.parseArray(jsonArray.toJSONString(),JSONObject.class);
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                long a = o1.getLongValue("time");
                long b = o2.getLong("time");
                if (a < b) {
                    return -1;
                } else if(a == b) {
                    return 0;
                } else
                    return 1;
            }
        });
        if(list.size()<10){
            return;
        }
        JSONObject jsonObject=list.get(0);
        String path=jsonObject.getString("file");
        File file1 = new File(path);
        if(file1.exists()){
            file1.delete();
        }
    }




}
